package com.info.examples.strategy.controller;

import com.info.examples.strategy.PromoteSalesService;
import com.info.examples.strategy.PromoteStrategyFactory;
import com.info.examples.strategy.PromoteTypeEnum;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Random;

@RestController
public class PromoteController {

    private final PromoteStrategyFactory strategyFactory;

    public PromoteController(PromoteStrategyFactory strategyFactory) {
        this.strategyFactory = strategyFactory;
    }

    @GetMapping("/getPrice/{price:^[1-9]\\d*$|^(?>[1-9]\\d*\\.\\d{1,8})$}")
    public String getPromotePrice(@PathVariable String price) {
        PromoteTypeEnum promoteType = new Random().nextInt(100) > 50 ? PromoteTypeEnum.FULL_REDUCTION : PromoteTypeEnum.DISCOUNT;
        final PromoteSalesService promoteSalesService = strategyFactory.getInstance(promoteType);
        final BigDecimal promotionPrice = promoteSalesService.getPromotionPrice(new BigDecimal(price));
        return String.format("原价 %s 使用 %s 促销后价格为 %f", price, promoteSalesService.getType(), promotionPrice.doubleValue());
    }
}
